package com.tenement.action;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tenement.domain.TenementLog;
import com.tenement.domain.TenementUser;
import com.tenement.service.LogService;
import com.tenement.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName : WeiXinAction  //类名
 * @Description : 微信接口  //描述
 * @Author : 易嵘  //作者
 * @Date: 2020-06-14 08:55  //时间
 */
@Controller
@RequestMapping("weiXinAction")
public class WeiXinAction {

    @Resource
    UserService userService;

    @Resource
    LogService logService;
    /**
     * 登录
     * @param code 使用登录凭证
     * @param session
     * @return
     */
    @RequestMapping(value="login")
    @ResponseBody
    public Map<String,Object> login(String code, HttpSession session , HttpServletRequest request) {
        Map map = new HashMap();
        map.put("status", 0);
        // 登录凭证不能为空
        if (code == null || code.length() == 0) {


            return map;
        }
        Map<String,Object> mp=fngWen(code);
        TenementUser man=new TenementUser();
        man.setWxUser((String)mp.get("openid"));
        man=userService.findWeiXin(man);
        if(man!=null){
            map.put("status", 1);
            session.setAttribute("user", man);
            String ip = request.getRemoteAddr(); //取登陆人的ip
            TenementLog log=new TenementLog();
            log.setLogId(UUID.randomUUID().toString().replaceAll("-",""));
            log.setLogTitle("用户登录");
            log.setLogType(0);
            Date date=new Date();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dates=sdf.format(date);
            Gson gson=new Gson();
            String json=gson.toJson(man);
            log.setLogBody(json+" 登录设备：PC");
            log.setLogIp(ip);
            log.setCreatedBy(man.getUserName());
            logService.add(log);
            map.put("data",man );
        }else{
            map.put("status", 2);

            map.put("usweiid",(String)mp.get("openid") );
        }
        return map;
    }

    /**
     *拼接参数
     * @param code 使用登录凭证
     * @return
     */
    private Map<String,Object>  fngWen(String code){

        // 小程序唯一标识 (在微信小程序管理后台获取)
        String wxspAppid = "wxe14b5f66e08b4cf2";
        // 小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "7a466a4abadca82cddc7aa91118b1f56";
        // 授权（必填）
        String grant_type = "authorization_code";

        //////////////// 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        // 请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type="
                + grant_type;
        // 发送请求
        String sr = sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        System.out.println(sr);

        Gson gson=new Gson();
        Map<String,Object> mp=gson.fromJson(sr,new TypeToken<Map<String, Object>>() {
        }.getType());
        // System.out.println(mp.get("openid"));

        return mp;
    }

    /**
     * 访问微信服务器
     * @param url 地址
     * @param param 参数
     * @return
     */
    private String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            System.out.println(urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段

            // 遍历所有的响应头字段

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
}
